package bai8.com.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import bai8.com.command.Message;

/**
 * @author nglehien Oct 21, 2012 - 8:44:26 PM
 */

public class ClientConnection {

	private Socket socket;
	private ObjectInputStream objectInputStream;
	private ObjectOutputStream objectOutputStream;

	public ClientConnection(String host, int port) throws UnknownHostException,
			IOException {
		socket = new Socket(host, port);
		if (socket.isConnected()) {
			objectOutputStream = new ObjectOutputStream(
					socket.getOutputStream());
			objectInputStream = new ObjectInputStream(socket.getInputStream());
		}
	}

	public void sendToServer(Message command) throws IOException {
		if (socket.isConnected()) {
			objectOutputStream.writeObject(command);
		}
	}

	public Message receiveFromServer() throws ClassNotFoundException {
		try {
			if (socket.isConnected()) {
				Message command = (Message) objectInputStream.readObject();
				return command;
			}
		} catch (IOException e) {
		}
		return null;
	}
}
